package com.bigboss.knowstar.controller;

import com.bigboss.knowstar.entity.Notice;
import com.bigboss.knowstar.entity.model.APIResult;
import com.bigboss.knowstar.exception.NoticeException;
import com.bigboss.knowstar.service.impl.NoticeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;

import static com.bigboss.knowstar.utils.ValidateData.validateData;

@RestController
@RequestMapping("/notice")
public class NoticeController {
    
    @Autowired
    private NoticeServiceImpl noticeService;

    @PostMapping("/{ClassId}")
    public APIResult noticeCreate(@PathVariable Integer ClassId, @RequestBody @Validated Notice notice, BindingResult result) {
        try {
            ArrayList<String> data = validateData(result);
            if (data != null) {
                return APIResult.error(data);
            }
            noticeService.createNotice(ClassId, notice);
            return APIResult.success("公告创建成功");
        } catch (NoticeException e) {
            return APIResult.error("公告创建失败:" + e.getMessage());
        }

    }

    @PutMapping("/{Nid}")
    public APIResult noticeUpdate(@PathVariable Integer Nid, @RequestBody Map<String, Object> fields) {
        try {
            noticeService.updateNotice(Nid, fields);
            return APIResult.success("公告更新成功");
        } catch (NoticeException e) {
            return APIResult.error("公告更新失败:" + e.getMessage());
        }
    }

    @DeleteMapping("/{Nid}")
    public APIResult noticeDelete(@PathVariable Integer Nid) {
        try {
            noticeService.deleteNotice(Nid);
            return APIResult.success("公告删除成功");
        } catch (NoticeException e) {
            return APIResult.error("公告删除失败:" + e.getMessage());
        }
    }

    @GetMapping("/{Nid}")
    public APIResult noticeQueryByNid(@PathVariable Integer Nid) {
        try {
            Notice notice = noticeService.getNotice(Nid);
            return APIResult.success(notice);
        } catch (NoticeException e) {
            return APIResult.error("公告查询失败:" + e.getMessage());
        }
    }
}
